#include "visibilitydisplayform.h"
#include "ui_visibilitydisplayform.h"
#include "../gloab/globalobserver.h"
#include "QsLog/QsLog.h"

#include <QSplineSeries>
#include <QValueAxis>
#include <QDateTimeAxis>
#include <QLegendMarker>



VisibilityDisplayForm::VisibilityDisplayForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::VisibilityDisplayForm)
    , m_startTime(QDateTime::currentDateTime())
{
    ui->setupUi(this);


    this->InitChart();
    this->InitTreeView();


    //Visibility解析数据后，连接所有的需要展示数据的地方，
    //右下角的一分钟能见度
    connect(GlobalObserver::getInstance(), &GlobalObserver::Sig_VisibilityProtocol, ui->circleProgressBar, &CircleProgressBar::Slot_UpdateValue);

    //通过全局连接器，将device的信号和show的槽函数进行连接
    connect(GlobalObserver::getInstance(), &GlobalObserver::Sig_VisibilityProtocol, this, &VisibilityDisplayForm::slot_Receive_DeviceVisibilityProtocol);

}



VisibilityDisplayForm::~VisibilityDisplayForm()
{
    delete ui;
}



//能见度仪展示数据界面的图表
#include <QPalette>
void VisibilityDisplayForm::InitTreeView()
{
    ui->tableView->setWindowTitle("数据列表");
    ui->tableView->setWindowIconText("数据列表");
    m_model.setRowCount(0);
    m_model.setColumnCount(6);
    m_model.setHorizontalHeaderLabels(QStringList() << "1分钟能见度"
                                                    << "10分钟能见度"<<"发射能量强度"
                                                    <<"接收能量强度"<<"设备状态码"<<"时间");

    QHeaderView *headerView = ui->tableView->horizontalHeader();
    // 设置样式表，包括背景颜色和字体样式
    headerView->setSectionResizeMode(QHeaderView::ResizeMode::Stretch);
    headerView->setStyleSheet("QHeaderView::section { background-color: #8da1ff; color: white }");
    headerView->setTextElideMode(Qt::TextElideMode::ElideMiddle);

    ui->tableView->setModel(&m_model);

}


void VisibilityDisplayForm::InitChart()
{

    this->m_visYMax.clear(); this->m_visYMax.push_back(INT_MIN);
    this->m_visYMin.clear(); this->m_visYMin.push_back(INT_MAX);
    m_chart = new QChart();

    m_series1 = new QSplineSeries(m_chart);
    m_series1->setPen(QPen(QBrush(Qt::blue),2, Qt::PenStyle::SolidLine,
                           Qt::PenCapStyle::RoundCap, Qt::PenJoinStyle::RoundJoin));

    m_series10 = new QSplineSeries(m_chart);
    m_series10->setPen(QPen(QBrush(Qt::green),2, Qt::PenStyle::SolidLine,
                            Qt::PenCapStyle::RoundCap, Qt::PenJoinStyle::RoundJoin));

    m_chart->addSeries(m_series1);
    m_chart->addSeries(m_series10);

    // 更改标题颜色和字体大小
    QFont titleFont("sans-serif", 12, QFont::Bold);
    m_chart->setTitleFont(titleFont);
    QBrush titleBrush(Qt::black);
    m_chart->setTitleBrush(titleBrush);

    // 设置y轴
    QValueAxis *axisY = new QValueAxis();
    axisY->setRange(0, 50000);
    axisY->setTickCount(6);
    axisY->setLabelFormat("%d");

    // 设置x轴
    QDateTimeAxis* axisX = new QDateTimeAxis;
    axisX->setTickCount(10);
    axisX->setFormat("hh:mm:ss");
    axisX->setRange(QDateTime::currentDateTime().addSecs(-60), QDateTime::currentDateTime().addMSecs(500));

    m_chart->addAxis(axisX, Qt::AlignBottom);
    m_chart->addAxis(axisY, Qt::AlignmentFlag::AlignLeft);

    m_series1->attachAxis(axisX);
    m_series1->attachAxis(axisY);

    m_series10->attachAxis(axisX);
    m_series10->attachAxis(axisY);

    m_chart->legend()->markers().at(0)->setVisible(true);
    m_chart->legend()->markers().at(0)->setFont(QFont("微软雅黑",12));
    m_chart->legend()->markers().at(0)->setPen(QPen(Qt::blue));
    m_series1->setName("一分钟能见度");

    m_chart->legend()->markers().at(1)->setVisible(true);
    m_chart->legend()->markers().at(1)->setFont(QFont("微软雅黑",12));
    m_chart->legend()->markers().at(1)->setPen(QPen(Qt::green));
    m_series10->setName("十分钟能见度");


    m_chart->legend()->attachToChart();

    ui->graphicsView->setChart(m_chart);
    ui->graphicsView->setRenderHint(QPainter::Antialiasing);


}



void VisibilityDisplayForm::slot_Receive_DeviceVisibilityProtocol(protocol::VisibilityProtocol point)
{
    qDebug()<<"开始更新";
//更新m_chart
    m_series1->append(point.m_date_time.toMSecsSinceEpoch(), point.m_one_minute_visibility);
    m_series10->append(point.m_date_time.toMSecsSinceEpoch(), point.m_ten_minute_visibility);
    //进数据，维护数组m_visYMax和m_visYMin
    int tempMax = std::max(point.m_one_minute_visibility, point.m_ten_minute_visibility);
    int tempMin = std::min(point.m_one_minute_visibility, point.m_ten_minute_visibility);
    if(!this->m_visYMax.empty() && tempMax > this->m_visYMax[0]){
        this->m_visYMax.clear();
    }
    else if(!this->m_visYMax.empty() && tempMax <= this->m_visYMax[0]){
        //删除数组中小于tempMax的值
        for(int i = 1; i < this->m_visYMax.size();){
            if(this->m_visYMax[i] < tempMax){
                this->m_visYMax.remove(i);
            }else{
                ++i;
            }
        }
    }
    this->m_visYMax.push_back(tempMax);

    if(!this->m_visYMin.empty() && tempMin < this->m_visYMin[0]){
        this->m_visYMin.clear();
    }
    else if(!this->m_visYMin.empty() && tempMin >= this->m_visYMin[0]){
        //删除数组中大于tempMin的值
        for(int i = 1; i < this->m_visYMin.size();){
            if(this->m_visYMin[i] > tempMin){
                this->m_visYMin.remove(i);
            }else{
                ++i;
            }
        }
    }
    this->m_visYMin.push_back(tempMin);


    if(m_series1->count() > 60 && m_series10->count() > 60){
        //出队的时候维护数组
        int tempMin = std::min(m_series1->at(0).y(), m_series10->at(0).y());
        int tempMax = std::max(m_series1->at(0).y(), m_series10->at(0).y());
        if(tempMax == this->m_visYMax[0]){
            this->m_visYMax.pop_front();
        }
        if(tempMin== this->m_visYMin[0]){
            this->m_visYMin.pop_front();
        }
        m_series1->removePoints(0, m_series1->count() - 60);
        m_series10->removePoints(0, m_series10->count() - 60);
    }

    QDateTime start = point.m_date_time.addSecs(-3600);
    QDateTime end = point.m_date_time.addMSecs(500);
    m_chart->axisX()->setRange(start, end);
    m_chart->axisY()->setRange(m_visYMin[0] - 1000, m_visYMax[0] + 1000);
    //axisX->setRange(start, end);
    //axisY->setRange(m_visYMin[0] - 1000, m_visYMax[0] + 1000);
    ui->graphicsView->update();

//更新表格
    int row = m_model.rowCount();
    if(row == 10){
        m_model.removeRows(0, 1);
        row--;
    }

    auto item = new QStandardItem(QString::asprintf("%d",point.m_one_minute_visibility));
    item->setTextAlignment(Qt::AlignCenter);
    m_model.setItem(row, 0, item);

    item = new QStandardItem(QString::asprintf("%d",point.m_ten_minute_visibility));
    item->setTextAlignment(Qt::AlignCenter);
    m_model.setItem(row, 1, item);

    item = new QStandardItem(QString::asprintf("%d",point.m_TheIntensityOfEmittedEnergy));
    item->setTextAlignment(Qt::AlignCenter);
    m_model.setItem(row, 2, item);

    item = new QStandardItem(QString::asprintf("%d",point.m_TheIntensityOfReceivedEnergy));
    item->setTextAlignment(Qt::AlignCenter);
    m_model.setItem(row, 3, item);

    item = new QStandardItem(point.m_deviceState);
    item->setTextAlignment(Qt::AlignCenter);
    m_model.setItem(row, 4, item);

    item = new QStandardItem(point.m_date_time.toString("yyyy/MM/dd HH:mm:ss"));
    item->setTextAlignment(Qt::AlignCenter);
    m_model.setItem(row, 5, item);

    ui->tableView->update();
    qDebug() << "更新图表currentThreadId： "<<" : "<<QThread::currentThreadId()<<"currentThread : " << QThread::currentThread();

}




















